package com.mchsdk.paysdk.dialog;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.mchsdk.paysdk.bean.login.AccountPopuWindow;
import com.mchsdk.paysdk.callback.PlatformLoginCallback;
import com.mchsdk.paysdk.config.MCHConstant;
import com.mchsdk.paysdk.utils.MCHInflaterUtils;
import com.mchsdk.paysdk.utils.MCLog;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PlatformLoginDialog extends DialogFragment implements
        View.OnFocusChangeListener, TextWatcher, View.OnLongClickListener {
    /**
     * 日志打印
     */
    private static final String TAG = "PlatformLogin";

    /**
     * 用户名
     **/
    protected static final String KEY_ACCOUNT = "mc_account";

    /**
     * 密码
     **/
    protected static final String KEY_PASSWORD = "mc_password";

    /**
     * 上下文
     */
    private Context mContent;
    /**
     * 是否记住密码
     */
    boolean isSavePwd;
    /**
     * 记住密码
     */
    Button btnSavePwd;

    /**
     * 返回键监听
     */
    private OnKeyListener mDialogKeyListener;

    /**
     * 登录
     */
    private PlatformLoginCallback mLoginCallback;

    /**
     * 忘记密码
     */
    private OnClickListener mForgmentPwdClick;

    /**
     * 注册
     */
    private OnClickListener mRegisterClick;

    /**
     * 快速注册
     */
    private OnClickListener mQuickRegisterClick;

    private OnClickListener mThirdLoginClick;
    private OnClickListener ll_qucklogin_click;
    LinearLayout ll_wblogin;
    LinearLayout ll_qqlogin;
    LinearLayout ll_wxlogin;
    LinearLayout ll_bdlogin;


    /**
     * 失去焦点事件
     */
    private View.OnFocusChangeListener mFocusChangeListener;

    /**
     * 用户名输入框
     */
    EditText edtAccount;


    /**
     * 密码输入框
     */
    EditText edtPassword;

    public PlatformLoginDialog() {
    }

    @SuppressLint("ValidFragment")
    public PlatformLoginDialog(Context con) {
        mContent = con;
    }


    /**
     * 加载logo的URL
     */
    private String path = MCHConstant.getInstance().getDownloadLogoUrl();
    //下载成功
    private static final int LOAD_SUCCESS = 1;

    //下载失败
    private static final int LOAD_FAIL = -1;

    private ImageView logoImg;

    private HttpURLConnection conn;

    private Bitmap bitmap;
    /**
     * 下载完成后更新UI
     */
    Handler uihandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LOAD_SUCCESS:
                    if (logoImg != null && bitmap != null) {
                        logoImg.setImageBitmap(bitmap);
                    }
                    MCLog.w(TAG, "下载logo成功");
                    break;
                case LOAD_FAIL:
                    MCLog.w(TAG, "下载logo失败 ");
                    break;
            }
        }
    };

    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View containerView = inflater.inflate(MCHInflaterUtils.getIdByName(mContent,
                "layout", "dialog_mch_platform_login"), container, false);

        // 如果有信息,显示加载信息
        Bundle bundle = getArguments();
        String account = "";
        String pwd = "";


        if (bundle != null) {
            account = bundle.getString(KEY_ACCOUNT, "");
            pwd = bundle.getString(KEY_PASSWORD, "");
        }
        isSavePwd = true;

        //加载logo

        addLogo(containerView);


        edtAccount = (EditText) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContent, "id", "edt_mc_platform_login_account"));
        if (!TextUtils.isEmpty(account)) {
            edtAccount.setText(account);
        }
//		edtAccount.addTextChangedListener(this);
//		edtAccount.setOnLongClickListener(this);
        edtPassword = (EditText) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContent, "id", "edt_mc_platform_login_password"));
        if (!TextUtils.isEmpty(pwd)) {
            edtPassword.setText(pwd);
        }

        TextView txtSavePwd = (TextView) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContent, "id", "txt_mc_save_password"));
        txtSavePwd.setOnClickListener(savePwdClick);
        btnSavePwd = (Button) containerView.findViewById(MCHInflaterUtils
                .getIdByName(mContent, "id", "btn_mc_save_password"));
        btnSavePwd.setBackgroundResource(MCHInflaterUtils.getIdByName(mContent,
                "drawable", "mc_platform_login_seleceted"));
        btnSavePwd.setOnClickListener(savePwdClick);

        Button btnRegister = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContent, "id",
                        "btn_mc_platform_toregister"));
        String str = btnRegister.getText().toString().trim();
//		SpannableString spastr = StrUtil.addLine(str, 3, 8);
//		spastr = StrUtil.addColor(spastr, 0xffffffff, 0, 3);
        btnRegister.setText(str);
        btnRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mRegisterClick) {
                    dismissAllowingStateLoss();
                    mRegisterClick.onClick(v);
                }
            }
        });

        Button btnQuickRegister = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContent, "id",
                        "btn_mc_platform_toquickregister"));
        btnQuickRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mQuickRegisterClick) {
//                    dismissAllowingStateLoss();
                    mQuickRegisterClick.onClick(v);
                }
            }
        });

        Button btnforgmentPwd = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContent, "id",
                        "btn_mc_platform_forgment_pwd"));

        String strbtnforgmentPwd = btnforgmentPwd.getText().toString().trim();
//		SpannableString spabtnforgmentPwd=StrUtil.addLine(strbtnforgmentPwd,4,8);
//		spabtnforgmentPwd=StrUtil.addColor(spabtnforgmentPwd,0xffffffff,0,4);

        btnforgmentPwd.setText(strbtnforgmentPwd);
        btnforgmentPwd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mForgmentPwdClick) {
                    mForgmentPwdClick.onClick(v);
                }
            }
        });

        Button btnLogin = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(mContent, "id",
                        "btn_mc_platform_login"));
        btnLogin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mLoginCallback) {
                    mLoginCallback.platformLogin(edtAccount.getText()
                            .toString().trim(), edtPassword.getText()
                            .toString().trim(), isSavePwd);
                }
            }
        });

		/*第三方登录按钮*/
        final int wbid = MCHInflaterUtils.getIdByName(mContent, "id", "ll_wblogin");
        final int qqid = MCHInflaterUtils.getIdByName(mContent, "id", "ll_qqlogin");
        final int wxid = MCHInflaterUtils.getIdByName(mContent, "id", "ll_wxlogin");
        final int bdid = MCHInflaterUtils.getIdByName(mContent, "id", "ll_bdlogin");
        View.OnClickListener thirdloginListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //LoadingDialog dialog = new LoadingDialog(mContent);
                //dialog.setCanceledOnTouchOutside(false);
                //dialog.show();
//                dismissAllowingStateLoss();
                mThirdLoginClick.onClick(v);
            }
        };
        LinearLayout ll_btv_wblogin = (LinearLayout) containerView.findViewById(wbid);
        ll_btv_wblogin.setTag("wb");
        LinearLayout ll_btv_qqlogin = (LinearLayout) containerView.findViewById(qqid);
        ll_btv_qqlogin.setTag("qq");
        LinearLayout ll_btv_wxlogin = (LinearLayout) containerView.findViewById(wxid);
        ll_btv_wxlogin.setTag("wx");
        LinearLayout ll_btv_bdlogin = (LinearLayout) containerView.findViewById(bdid);
        ll_btv_bdlogin.setTag("bd");
        ll_btv_wblogin.setOnClickListener(thirdloginListener);
        ll_btv_qqlogin.setOnClickListener(thirdloginListener);
        ll_btv_wxlogin.setOnClickListener(thirdloginListener);
        ll_btv_bdlogin.setOnClickListener(thirdloginListener);

        ll_wblogin = (LinearLayout) containerView.findViewById(
                MCHInflaterUtils.getIdByName(mContent, "id", "ll_mch_wblogin"));
        ll_wblogin.setVisibility(View.GONE);
        ll_qqlogin = (LinearLayout) containerView.findViewById(
                MCHInflaterUtils.getIdByName(mContent, "id", "ll_mch_qqlogin"));
        ll_qqlogin.setVisibility(View.GONE);
        ll_wxlogin = (LinearLayout) containerView.findViewById(
                MCHInflaterUtils.getIdByName(mContent, "id", "ll_mch_wxlogin"));
        ll_wxlogin.setVisibility(View.GONE);
        ll_bdlogin = (LinearLayout) containerView.findViewById(
                MCHInflaterUtils.getIdByName(mContent, "id", "ll_mch_bdlogin"));
        ll_bdlogin.setVisibility(View.GONE);

        setCancelable(false);
        this.getDialog().setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dismissAllowingStateLoss();
                    if (null != mDialogKeyListener) {
                        mDialogKeyListener.onKey(dialog, keyCode, event);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });

        return containerView;
    }

    /**
     * 加载图 logo
     */
    private void addLogo(View view) {

        logoImg = (ImageView) view.findViewById(MCHInflaterUtils
                .getIdByName(mContent, "id", "mch_iv_log"));
        new Thread(new Runnable() {
            @Override
            public void run() {


                getBitmap();
            }


        }).start();
    }

    private void getBitmap() {
        URL url = null;

        InputStream is = null;

        try {
            url = new URL(path);

            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");

            conn.connect();

            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);

                uihandler.sendEmptyMessage(LOAD_SUCCESS);
            }

        } catch (MalformedURLException e) {
            uihandler.sendEmptyMessage(LOAD_FAIL);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

                try {
                    if (is != null) {
                        is.close();
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }


    OnClickListener savePwdClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            isSavePwd = !isSavePwd;
            if (isSavePwd) {
                btnSavePwd.setBackgroundResource(MCHInflaterUtils.getIdByName(mContent,
                        "drawable", "mc_platform_login_seleceted"));
            } else {
                btnSavePwd.setBackgroundResource(MCHInflaterUtils.getIdByName(mContent,
                        "drawable", "mc_platform_login_unseleceted"));
            }
        }
    };

    public void setmDialogKeyListener(OnKeyListener mDialogKeyListener) {
        this.mDialogKeyListener = mDialogKeyListener;
    }

    public void setmLoginCallback(PlatformLoginCallback mLoginCallback) {
        this.mLoginCallback = mLoginCallback;
    }

    public void setmForgmentPwdClick(OnClickListener mForgmentPwdClick) {
        this.mForgmentPwdClick = mForgmentPwdClick;
    }

    public void setmRegisterClick(OnClickListener mRegisterClick) {
        this.mRegisterClick = mRegisterClick;
    }

    public void setmQuickRegisterClick(OnClickListener mQuickRegisterClick) {
        this.mQuickRegisterClick = mQuickRegisterClick;
    }

    public void setThirdLoginClick(OnClickListener thirdLoginClick) {
        this.mThirdLoginClick = thirdLoginClick;
    }

    //判断是否开起第三方登录
    public void setThirdLoginButtonShow(boolean iswb, boolean isqq,
                                        boolean iswx, boolean isbd) {
        ll_wblogin.setVisibility(iswb ? View.VISIBLE : View.GONE);
        ll_qqlogin.setVisibility(isqq ? View.VISIBLE : View.GONE);
        ll_wxlogin.setVisibility(iswx ? View.VISIBLE : View.GONE);
        ll_bdlogin.setVisibility(isbd ? View.VISIBLE : View.GONE);
    }

    public void setLl_qucklogin_click(OnClickListener ll_qucklogin_click) {
        this.ll_qucklogin_click = ll_qucklogin_click;
    }

    public void setmOnfocusChangeLinser(View.OnFocusChangeListener mFocusChangeListener) {
        this.mFocusChangeListener = mFocusChangeListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置对话框的样式
        setStyle(STYLE_NO_FRAME, MCHInflaterUtils.getIdByName(mContent, "style", "MCCustomDialog"));
    }

    @SuppressLint("NewApi")
    @Override
    public void onStart() {
        // 1, 设置对话框的大小
        Window window = getDialog().getWindow();
        WindowManager wm = window.getWindowManager();
        Point windowSize = new Point();
        wm.getDefaultDisplay().getSize(windowSize);
        float size_x = 0;
        float size_y = 0;
        int width = windowSize.x;
        int height = windowSize.y;
        if (width >= height) {// 横屏
            size_x = 0.7f;
            size_y = 0.8f;
            window.getAttributes().width = (int) (windowSize.y * size_y * 1.1);
            window.getAttributes().height = (int) (windowSize.y * size_y);
        } else {// 竖屏
            size_x = 0.9f;
            size_y = 0.855f;
            window.getAttributes().width = (int) (windowSize.x * size_x);
            window.getAttributes().height = (int) (windowSize.x * size_y);
        }
        window.setGravity(Gravity.CENTER);
        super.onStart();
    }

    public static class Builder {
        /**
         * 存放数据的容器
         **/
        private Bundle mmBundle;

        private OnKeyListener mmDialogKeyListener;
        private PlatformLoginCallback mmLoginCallback;
        private OnClickListener mmForgmentPwdClick;
        private OnClickListener mmRegisterClick;
        private OnClickListener mmQuickRegisterClick;
        private OnClickListener mmThirdLoginClick;
        //		private OnClickListener mmll_wblogin_click;
//		private OnClickListener mmll_qqlogin_click;
//		private OnClickListener mmll_wxlogin_click;
//		private OnClickListener mmll_bdlogin_click;
        private OnClickListener mmll_qucklogin_click;

        public Builder() {
            mmBundle = new Bundle();
        }

        public Builder setAccount(CharSequence account) {
            mmBundle.putCharSequence(KEY_ACCOUNT, account);
            return this;
        }

        public Builder setPassword(CharSequence pwd) {
            mmBundle.putCharSequence(KEY_PASSWORD, pwd);
            return this;
        }

        public Builder setDialogKeyListener(OnKeyListener mmDialogKeyListener) {
            this.mmDialogKeyListener = mmDialogKeyListener;
            return this;
        }

        public Builder setLoginCallback(PlatformLoginCallback mmLoginCallback) {
            this.mmLoginCallback = mmLoginCallback;
            return this;
        }

        public Builder setRegisterClick(OnClickListener mmRegisterClick) {
            this.mmRegisterClick = mmRegisterClick;
            return this;
        }

        public Builder setQuickRegisterClick(
                OnClickListener mmQuickRegisterClick) {
            this.mmQuickRegisterClick = mmQuickRegisterClick;
            return this;
        }

        public Builder setMmll_qucklogin_click(OnClickListener mmll_qucklogin_click) {
            this.mmll_qucklogin_click = mmll_qucklogin_click;
            return this;
        }

        public Builder setThirdLoginClick(OnClickListener thirdLoginClick) {
            this.mmThirdLoginClick = thirdLoginClick;
            return this;
        }

//		public Builder setMmll_wblogin_click(OnClickListener mmll_wblogin_click) {
//			this.mmll_wblogin_click = mmll_wblogin_click;
//			return this;
//		}
//
//		public Builder setMmll_qqlogin_click(OnClickListener mmll_qqlogin_click) {
//			this.mmll_qqlogin_click = mmll_qqlogin_click;
//			return this;
//		}
//
//		public Builder setMmll_wxlogin_click(OnClickListener mmll_wxlogin_click) {
//			this.mmll_wxlogin_click = mmll_wxlogin_click;
//			return this;
//		}
//
//		public Builder setMmll_bdlogin_click(OnClickListener mmll_bdlogin_click) {
//			this.mmll_bdlogin_click = mmll_bdlogin_click;
//			return this;
//		}

        public Builder setForgmentPwdClick(OnClickListener mmForgmentPwdClick) {
            this.mmForgmentPwdClick = mmForgmentPwdClick;
            return this;
        }

        private PlatformLoginDialog create(Context context) {
            final PlatformLoginDialog dialog = new PlatformLoginDialog(context);
            // 1,设置显示内容
            dialog.setArguments(mmBundle);

            dialog.setmDialogKeyListener(mmDialogKeyListener);
            dialog.setmLoginCallback(mmLoginCallback);
            dialog.setmForgmentPwdClick(mmForgmentPwdClick);
            dialog.setmRegisterClick(mmRegisterClick);
            dialog.setmQuickRegisterClick(mmQuickRegisterClick);
            dialog.setThirdLoginClick(mmThirdLoginClick);
//			dialog.setLl_wblogin_click(mmll_wblogin_click);
//			dialog.setLl_bdlogin_click(mmll_bdlogin_click);
//			dialog.setLl_qqlogin_click(mmll_qqlogin_click);
//			dialog.setLl_wxlogin_click(mmll_wxlogin_click);
            dialog.setLl_qucklogin_click(mmll_qucklogin_click);
            return dialog;
        }

        public PlatformLoginDialog show(Context context, FragmentManager fm) {
            if (fm == null) {
                MCLog.e(TAG, "show error : fragment manager is null.");
                return null;
            }

            PlatformLoginDialog dialog = create(context);
            MCLog.d(TAG, "show SelectPTBTypeDialog.");
//			dialog.show(fm, TAG);

            FragmentTransaction ft = fm.beginTransaction();
            ft.add(dialog, TAG);
            ft.show(dialog);
            ft.commitAllowingStateLoss();
            return dialog;
        }
    }

    //	@Override
//	public void show(FragmentManager manager, String tag) {
//		FragmentTransaction ft = manager.beginTransaction();
//		ft.add(this, tag);
//        ft.commitAllowingStateLoss();
//	}
    @Override
    public void onFocusChange(View v, boolean hasFocus) {//焦点改变
        EditText dd = (EditText) v;
        int edtAccount = MCHInflaterUtils.getIdByName(mContent, "id",
                "edt_mc_platform_login_account");
        if (v.getId() == edtAccount && !hasFocus) {// 手机号失去焦点
            if (null != mFocusChangeListener) {
                mFocusChangeListener.onFocusChange(v, hasFocus);
            }
            return;
        }
    }

    @Override
    public boolean onLongClick(View view) {//长按事件
        System.out.print("长按事件");
        showAccountList(((EditText) view).getText().toString().trim());

        return false;
    }

    @Override//文字改变响应事件
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//		showAccountList(charSequence.toString());
    }

    @Override//文字改变之前
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override//文字改变之后
    public void afterTextChanged(Editable editable) {
    }

    private void showAccountList(String tmp) {
        AccountPopuWindow aa = new AccountPopuWindow();
        aa.act = (Activity) mContent;
        aa.etNumber = edtAccount;
        aa.etPassword = edtPassword;
        aa.showSelectNumberDialog();
    }

}
